<?php

namespace App\Http\Controllers\Port;

use App\Http\Controllers\Controller;
use App\Http\Controllers\SlideVerifyController;
use App\Models\CompetiteActivity;
use App\Models\CompetiteActivityGroup;
use App\Models\CompetiteActivityGroupLoginLog;
use App\Validate\CompetiteActivityGroupValidate;
use Illuminate\Http\Request;
use Kkokk\Poster\PosterManager;
use Mews\Captcha\Facades\Captcha;

/**
 * 团队账号登录界面
 */
class GroupLoginController extends Controller
{

    public $request = null;
    public $model = null;
    public $validateObj = null;

    public function __construct(Request $request)
    {
        $this->request = $request;
        $this->model = new CompetiteActivityGroup();
        $this->validateObj = new CompetiteActivityGroupValidate();
    }

    /**
     * 团队账号登录
     * @param con_id 大赛id  
     * @param account 账号  
     * @param password 密码  
     * @param captcha string  验证码  默认  5位
     * @param key_str  string 验证码字符串 （获取验证码时返回的key值）
     */
    public function login()
    {
        //增加验证场景进行验证
        if (!$this->validateObj->scene('web_login')->check($this->request->all())) {
            return response()->json(['code' => 201,  'msg' => $this->validateObj->getError()]);
        }
        $con_id = $this->request->con_id;
        // $slideVerifyObj = new SlideVerifyController();
        // if (!PosterManager::Captcha()->type($slideVerifyObj->type)->check($this->request->key_str, $this->request->captcha, 3)) {
        //     return response()->json(['code' => 207,  'msg' => '验证失败，请重试！']);
        // }

        //判断当期活动是否支持团队上传
        $deliver_way = CompetiteActivity::where('id', $con_id)->where('is_del', 1)->where('is_play', 1)->value('deliver_way');
        if (empty($deliver_way) || $deliver_way == 2) {
            return response()->json(['code' => 201,  'msg' => '登录失败，此大赛不存在或不支持团队账号登录']);
        }

        //验证密码
        $validate_password = validate_password($this->request->password);
        if ($validate_password !== true) {
            return response()->json(['code' => 201,  'msg' => $validate_password]);
        }

        $res = $this->model->where('con_id', $con_id)->where('account', $this->request->account)->where('is_del', 1)->first();
        if (empty($res)) {
            return response()->json(['code' => 202,  'msg' => '此账号不存在']);
        }

        //判断账号是否被锁定
        $competiteActivityGroupLoginLogModel = new CompetiteActivityGroupLoginLog();
        $is_lock_ed = $competiteActivityGroupLoginLogModel->isLockEd($res['id']);
        if ($is_lock_ed) {
            return response()->json(['code' => 202,  'msg' => '此账号密码输入次数过多，已被锁定，请稍后重试']);
        }

        if ($res->password != md5($this->request->password)) {
            $is_lock = $competiteActivityGroupLoginLogModel->isLock($res['id']);
            $is_lock = $is_lock ? 2 : 1;
            $competiteActivityGroupLoginLogModel->insertLoginLog($res->id,  request()->ip(), 2, $is_lock); //添加错误日志
            return response()->json(['code' => 202,  'msg' => '密码输入不正确']);
        }

        /*生成token*/
        $res->token = get_guid();
        $result = $res->save();

        if (!$result) {
            return response()->json(['code' => 202,  'msg' => '登录失败,请稍后重试']);
        }

        //判断是否是初始密码  账号  加上 123 就是初始密码
        if ($res->password == $res->account . '123') {
            $is_modify_pwd = true; //初始密码，需要修改
        } else {
            $is_modify_pwd = false; //不是初始密码，需要修改
        }

        //添加登录日志
        $competiteActivityGroupLoginLogModel->insertLoginLog($res->id,  request()->ip());

        $tokenInfo['is_modify_pwd'] = $is_modify_pwd; //返回是否需要修改密码
        $tokenInfo['username'] = $res['name'];
        $tokenInfo['account'] = $res['account'];
        $tokenInfo['group_token'] = $res->token;
        $tokenInfo['head_img'] = $res->img;

        return response()->json(['code' => 200,  'msg' => '登录成功', 'content' => $tokenInfo]);
    }




    /**
     * 获取图形验证码   (需要现在中间件中开始session，不然会一直验证不通过)
     */
    public function getCaptcha()
    {
        //     $data = Captcha::src('flat');
        //     $data = Captcha::src();

        //     return response()->json(['code'=>200,  'msg'=>'获取成功','content'=>['captcha_url'=>$data]]);

        return response()->json(['code' => 200,  'msg' => '获取成功', 'content' => Captcha::create('flat', true)]); //flat 要与 验证器captcha里面的 值一致 


    }

    /**
     * 获取用户token 及失效时间
     */
    public function getTokenExpireTime()
    {
        $data['token'] = get_guid();
        $data['expire_time'] = date("Y-m-d H:i:s", (time() + config('other.admin_token_refresh_time')));
        return $data;
    }
}
